var core = require('core');
var wechat = core.wechat;
var config = wechat.config;
var send = core.send;
var querystring = require('querystring');
var step = core.step;

var GET = function(req, res, next){

    var query = req.query;
    var state = query.state ? JSON.parse(query.state) : query.state;
    var status = query.status;
    var token = query.token ? query.token : ( state ? state.token : null );
    var errcode = query.errcode;
    var ooid = query.ooid ? query.ooid : ( state ? state.ooid : null );
    var code = query.code;

    if(!state && ooid && token && !status && !code && !errcode){
        core.api("open/getToken", {token: token, type: "TempToken"}, function(err, body){
            if(err || !body.docs || body.code || body.docs.data)
                res.redirect(wechat.config.URL+"open/merchant_create?errcode=300000#msg_warn");
            else{
                res.redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ wechat.config.AppID +"&redirect_uri="+ wechat.config.URL+"open/merchant_create&response_type=code&scope=snsapi_base&state="+(
                    JSON.stringify({
                        token : token,
                        ooid  : ooid
                    })
                )+"#wechat_redirect");
            }
        });
    }else if(state && code && token && ooid && !status && !errcode){
        var param = {
            appid : wechat.config.AppID,
            secret : wechat.config.AppSecret,
            code : code,
            grant_type : 'authorization_code'
        };
        wechat.api.get('sns/oauth2/access_token', param, function(err, body){
            if(err || errcode)
                res.redirect(wechat.config.URL+"open/merchant_create?errcode=100001#msg_warn");
            else{
                core.api('open/upToken', { token: token, type: "TempToken", data: JSON.stringify({oid: body.openid, ooid: ooid, type: 0}) }, function(err, body){
                    if(err || body.code)
                        return res.redirect(wechat.config.URL+"open/merchant_create?errcode=200000#msg_warn");
                    else
                        res.redirect(wechat.config.URL+"open/merchant_create?status=true&token="+token+"#merchant_create");
                });

            };
        });
    }else if(status && token && !errcode){
        var SEND = new send(0);
        SEND.docs = {
            token : token,
            jssdk : wechat.getJSSDK(req.originalUrl)
        };

        res.render('open/merchant_create', SEND);
    }else if(errcode){
        var error = new send(parseInt(errcode));
        error.docs = {
            jssdk : wechat.getJSSDK(req.originalUrl)
        };
        res.render("open/merchant_create", error);
    };

};

var POST = function(req, res, next){

    var body = req.body;
    var token = body.token;
    var tokenType = "TempToken";
    var tag_id = [wechat.config.tagid_contrast[2], wechat.config.tagid_contrast[3]];
    var user, mechant, SEND;

    var getToken = function(){
        var that = this;
        core.api("open/getToken", {type: tokenType, token: token}, function(err, doc){
            that.step({err: err, doc: doc});
        });
    };

    var getTokenEnd = function(result){
        var err = result.err;
        var doc = result.doc;
        var that = this;
        if(err){
            SEND = new send(300000);
            return that.end();
        };
        if(doc.code){
            SEND = doc;
            return that.end();
        }

        doc = doc.docs;
        doc.data = JSON.parse(doc.data);

        body.admin = doc.data.oid;

        // body.recommend = doc.data.ooid;

        core.api("open/deleteToken", {token: token, type : tokenType});
        return true;
    };

    var addMerchant = function(){
        var that = this;
        core.api("merchant/add", body, function(err, doc){
            return that.step({err: err, doc: doc});
        });
    };

    var addMerchantEnd = function(result){
        var err = result.err;
        var doc = result.doc;
        var that = this;
        if(err){
            SEND = new send(300000);
            return that.end();
        };
        if(doc.code){
            SEND = doc;
            return that.end();
        }
        merchant = doc.docs;

        return true;
    };

    // var getUser = function(){
    //     var that = this;
    //     var params = {
    //         openid: body.admin,
    //         $or: JSON.stringify([{tagid_list: tag_id[0]}, {tagid_list: tag_id[1]}])
    //     };
    //
    //     core.api("user/getUser", params, function(err, doc){
    //         return that.step({err: err, doc: doc});
    //     });
    // }
    //
    // var getUserEnd = function(result){
    //     var err = result.err;
    //     var doc = result.doc;
    //     var that = this;
    //     if(err){
    //         SEND = new send(300000);
    //         return that.end();
    //     };
    //     if(doc.code && doc.code !== 100201){
    //         SEND = doc;
    //         return that.end();
    //     }
    //
    //     if(doc.code === 100201){
    //         var params = [{
    //             url : "members/batchtagging",
    //             openid_list : [body.admin],
    //             tagid : tag_id[0]
    //         },params = {
    //             url : "members/batchtagging",
    //             openid_list : [body.admin],
    //             tagid : tag_id[1]
    //         }];
    //         wechat.api.list.user.tags(params[0], function(err, doc){
    //             wechat.api.list.user.tags(params[1]);
    //         });
    //
    //         return that.step(tag_id);
    //
    //     }else{
    //         user = doc.docs;
    //         var nulltagid = null;
    //         var newtagid = {};
    //         // for(var x = 0; x < tag_id.length; x++){
    //         //     var thistag = false;
    //         //     for(var y = 0; y < user.tagid_list.length; y++){
    //         //         if(user.tagid_list[y] == tag_id[x]){
    //         //             thistag = true;
    //         //             break;
    //         //         };
    //         //     };
    //         //
    //         //     if(thistag){
    //         //         nulltagid = tag_id[x];
    //         //         break;
    //         //     };
    //         // };
    //         for(var x = 0; x < tag_id.length; x++){
    //             newtagid[tag_id[x]] = true;
    //         }
    //         for(var x = 0; x < tag_id.length; x++){
    //             var thistag = false;
    //             for(var y = 0; y < user.tagid_list.length; y++){
    //                 if(user.tagid_list[y] == tag_id[x])
    //                     delete newtagid[tag_id[x]];
    //             }
    //         };
    //
    //         for(var i in newtagid)
    //             nulltagid = parseInt(i);
    //
    //         if(!nulltagid)
    //             return that.step(new send(0));
    //
    //         var params = {
    //             url : "members/batchtagging",
    //             openid_list : [body.admin],
    //             tagid : nulltagid
    //         };
    //         wechat.api.list.user.tags(params);
    //         return that.step([nulltagid]);
    //     }
    // };
    //
    // var upUser = function(result){
    //     var that = this;
    //     var openid = body.admin;
    //     var update = {
    //         $addToSet: {
    //             tagid_list: {
    //                 $each : result
    //             },
    //             merchant: parseInt(merchant.mid)
    //         }
    //     };
    //
    //     var params = {
    //         openid : openid,
    //         update : JSON.stringify(update)
    //     };
    //     core.api("user/upUser", params, function(err, doc){
    //         return that.step({err: err, doc: doc});
    //     });
    // };

    var end = function(result){
        var err = result.err;
        var doc = result.doc;
        if(err)
            SEND = new send(300000);

        if(doc && doc.code)
            SEND = doc;

        return res.send(SEND);
    }
    step.Step(getToken, getTokenEnd, addMerchant, addMerchantEnd, end);
};

exports.GET = GET;
exports.POST = POST;
